import 'debug_utils.dart';

typedef T? DataParseCallback<T>(var data);

class ResponseData<T> {
  ResponseData();

  static const num kCodeSuccess = 200;

  late num code;
  dynamic? data;
  T? dataModel;
  late String msg;

  get success {
    return code == kCodeSuccess;
  }

  factory ResponseData.fromJson(Map<String, dynamic> json,
      {DataParseCallback<T>? dataParseCallback}) {
    ResponseData<T> responseData = ResponseData();
    try {
      responseData = _$ResponseDataFromJson(json);
      if (responseData.success &&
          responseData.data != null &&
          dataParseCallback != null) {
        responseData.dataModel = dataParseCallback(responseData.data);
        return responseData;
      }
    } on Error catch (e) {
      Debug.info(e.toString());
      Debug.info(e.stackTrace.toString());
      responseData.code = 403;
      responseData.msg = "数据解析错误";
    }
    return responseData;
  }

  Map<String, dynamic> toJson() => _$ResponseDataToJson(this);
}



// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

ResponseData<T> _$ResponseDataFromJson<T>(Map<String, dynamic> json) => ResponseData<T>()
  ..code = json['code'] as num
  ..data = json['data']
  ..msg = json['msg'] as String;

Map<String, dynamic> _$ResponseDataToJson(ResponseData instance) =>
    <String, dynamic>{
      'code': instance.code,
      'success': instance.success,
      'data': instance.data,
      'msg': instance.msg,
    };
